package brinaryTree;

import brinaryTree.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;

public class N222_CountCompleteTreeNodes {
    public int countNodes(TreeNode root) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        int count = 0;
        if (root != null) deque.add(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            count += size;
            for (int i = 0; i < size; i++) {
                TreeNode node = deque.pop();
                if (node.left != null) deque.add(node.left);
                if (node.right != null) deque.add(node.right);
            }
        }
        return count;
    }

    public int countNodes_recursion(TreeNode root) {
        if (root == null) return 0;
        return 1 + countNodes_recursion(root.left) + countNodes_recursion(root.right);
    }

    public int countNodes_recursion2(TreeNode root) {
        if (root == null) return 0;
        int leftHeight = 0, rightHeight = 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        while (left != null) {
            left = left.left;
            leftHeight++;
        }
        while (right != null) {
            right = right.right;
            rightHeight++;
        }
        if (rightHeight == leftHeight) {
            return (2 << leftHeight) - 1;
        }

        return countNodes_recursion2(root.left) + countNodes_recursion2(root.right) + 1;
    }
}